package cn.edu.scnu.controller;

import cn.edu.scnu.entity.Movie;
import cn.edu.scnu.entity.User;
import cn.edu.scnu.service.MovieService;
import cn.edu.scnu.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private MovieService movieService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 地区
    private List<String> areaList = List.of("内地", "港澳台", "韩国", "日本", "欧美", "其他区域");
    // 类型
    private List<String> typeList = List.of("爱情", "动画", "悬疑", "喜剧", "动作", "其他类型");

    // 首页
    @RequestMapping("/index")
    public String index(HttpSession session, Model model) {
        // 判断用户是否已登录
        if (session.getAttribute("userLogin") != null) {
            User user = (User)session.getAttribute("userLogin");
            redisTemplate.opsForValue().set("userLogin", user);
            model.addAttribute("userLogin", user);
        }
        return "index";
    }

    // 电影展示
    @RequestMapping("/index/movieList")
    @ResponseBody
    public Map<String, Object> showMovieList(
            @RequestParam("query") String query,
            @RequestParam("pageNo") Integer pageNo,
            @RequestParam("pageSize") Integer pageSize) {
        // 指定查询电影的方式（所有、按地区筛选、按类型筛选）
        List<Movie> movieList = findMovie(query);
        // 数据分页
        int from = Math.min(pageSize * pageNo, movieList.size());
        int to = Math.min(pageSize * (pageNo + 1), movieList.size());
        List<Movie> moviePages = movieList.subList(from, to);
        Map<String, Object> map = new HashMap<>();
        map.put("moviePages", moviePages);
        map.put("total", Math.ceil((double) movieList.size() / pageSize));
        return  map;
    }

    // 注册
    @RequestMapping("toRegister")
    public String toRegister() { return "register"; }

    @RequestMapping("/register")
    @ResponseBody
    public String register(String phone, String password, String userName) {
        if (phone.length() != 11) {
            return "手机号长度不正确！";
        }
        User user = userService.getById(phone);
        if (user == null) {
            userService.register(phone, password, userName);
            return "注册成功";
        } else {
            return "该手机号已被注册！";
        }
    }

    // 登录
    @RequestMapping("/toLogin")
    public String toLogin() { return "login"; }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String phone, String password, HttpSession session) {
        User loginUser = userService.login(phone, password);
        if (loginUser != null) {
            session.setAttribute("userLogin", loginUser);
            session.setAttribute("phone", phone); // 将手机号存储在会话中

            return "登录成功";
        } else {
            return "登录失败";
        }
    }

    // 退出登录
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        session.removeAttribute("userLogin");
        redisTemplate.opsForValue().set("userLogin", null);
        return "redirect:/index";
    }

    // 查询电影
    private List<Movie> findMovie(String query) {
        List<Movie> movieList = new ArrayList<>();
        if (query.equals("all")) {
            // 展示所有电影
            movieList = movieService.showAllMovie();
        } else {
            if (areaList.contains(query)) {
                // 根据地区筛选
                movieList = movieService.findMovieByArea(query);
            } else if (typeList.contains(query)) {
                // 根据类型筛选
                movieList = movieService.findMovieByType(query);
            }
        }
        return movieList;
    }

    @RequestMapping("/checkLoginStatus")
    @ResponseBody
    public Map<String,Object> checkLoginStatus(HttpSession session){
        Map<String,Object> response = new HashMap<>();
        User user = (User) session.getAttribute("userLogin");
        if(user != null){
            response.put("loggedIn",true);
            response.put("username",user.getUserName());
        }else{
            response.put("loggedIn",false);
        }
        return response;
    }

}
